package com.cn.jinl.service;

import com.cn.jinl.api.IComplainHandleService;
import com.cn.jinl.api.IFileInfoService;
import com.cn.jinl.conf.Config;
import com.cn.jinl.dao.ComplainHandleMapper;
import com.cn.jinl.dao.DepartmentMapper;
import com.cn.jinl.domain.ComplainHandle;
import com.cn.jinl.domain.ComplainHandleExample;
import com.cn.jinl.domain.FileInfo;
import com.cn.jinl.utils.*;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.Base64;
import java.util.List;
import java.util.Map;

/**
 * Created On : 2024/1/15.
 * <p>
 * Author : Huiyan
 * <p>
 * Description: ComplainHandleServiceImpl
 */
@Service
public class ComplainHandleServiceImpl implements IComplainHandleService {

    @Autowired
    private ComplainHandleMapper complainHandleMapper;

    @Autowired
    private GenerateUUID generateUUID;

    @Autowired
    private DepartmentMapper departmentMapper;

    @Autowired
    private IFileInfoService fileInfoService;

    @Autowired
    private Config config;

    @Autowired
    private HttpServletRequest request;


    @Override
    public List<ComplainHandle> getComplainHandleList(QueryForm queryForm) throws Exception {

        List<ComplainHandle> list = complainHandleMapper.getComplainHandleList(queryForm);

        return list;
    }

    @Override
    public String addComplainHandle(ComplainHandle complainHandle) throws Exception {

        if (null == complainHandle){
            return "请输入投诉信息";
        }

        String result = this.complainAddLeagal(complainHandle);
        if (!"".equals(result)){
            return result;
        }

        String id = CommonUtil.generateRandomNum("complain_");
        complainHandle.setId(id);

        String key = "TS"+generateUUID.getYearStr();
        int num = generateUUID.getNumberFlag(key);
        String code = key+generateUUID.getTwoNumStr(num);
        complainHandle.setComplainCode(code);

        complainHandle.setAcceptStatus("0");

        //get accept_department
        String acceptDepartmentName = this.getDeptName(complainHandle.getUserId());
        complainHandle.setAcceptDeptName(acceptDepartmentName);

        int count = complainHandleMapper.insertSelective(complainHandle);

        if (count < 1){
            return CommonUtil.outStr(count);
        }

        //picture
        List<FileInfo> fileInfos = complainHandle.getFileInfos();
        if (!CollectionsUtil.isEmpty(fileInfos)){
            for (FileInfo fileInfo : fileInfos){
                fileInfo.setRelateId(id);
            }
            result = fileInfoService.batchAddFile(fileInfos);
            if (StringUtils.isNotEmpty(result)){
                throw new Exception("插入文件异常");
            }
        }
        return "";
    }

    @Override
    public String updateComplainHandle(ComplainHandle complainHandle) throws Exception {

        String id = complainHandle.getId();

        if (StringUtils.isEmpty(id)){
            return "id is null";
        }

        String result = this.complainUpdateLeagal(complainHandle);
        if (!"".equals(result)){
            return result;
        }

        if ("0".equals(complainHandle.getAcceptStatus())){
            String acceptDeptName = this.getDeptName(complainHandle.getUserId());
            complainHandle.setAcceptDeptName(acceptDeptName);
        }else if ("1".equals(complainHandle.getAcceptStatus())){
            String handleDeptName = this.getDeptName(complainHandle.getUserId());
            complainHandle.setHandleDeptName(handleDeptName);
        }

        ComplainHandleExample example = new ComplainHandleExample();
        example.createCriteria().andIdEqualTo(id).andStatusEqualTo(Constants.NORMAL_STATUS);

        int count = complainHandleMapper.updateByExampleSelective(complainHandle,example);

        return CommonUtil.outStr(count);
    }

    @Override
    public String deleteComplainHandle(QueryForm queryForm) throws Exception {

        List<String> ids = queryForm.getIds();
        if (CollectionsUtil.isEmpty(ids)){
            return "delete id is null";
        }

        ComplainHandle complainHandle = new ComplainHandle();
        complainHandle.setStatus(Constants.DEL_STATUS);
        ComplainHandleExample example = new ComplainHandleExample();
        example.createCriteria().andIdIn(ids);

        int count = complainHandleMapper.updateByExampleSelective(complainHandle,example);

        return CommonUtil.outStr(count);
    }

    @Override
    public String downloadComplainHandlePDF(QueryForm queryForm) throws Exception {
        String id = queryForm.getId();
        if (StringUtils.isEmpty(id)){
            return "id is null";
        }

        Map<String,Object> result = Maps.newHashMap();

        ComplainHandle complainHandle = complainHandleMapper.selectByPrimaryKey(id);
        result.put("complain",complainHandle);

        List<FileInfo> fileInfos = fileInfoService.queryFileListByRelateId(id);
        for(FileInfo fileInfo:fileInfos){
            String filePath = fileInfo.getFilePath();
            BufferedImage image = ImageIO.read(new File(filePath));
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            String defaultImageType = "png";
            int index = filePath.lastIndexOf(".");
            if(index > -1){
                defaultImageType = filePath.substring(index+1);
            }
            ImageIO.write(image, defaultImageType, baos);
            byte[] imageBytes = baos.toByteArray();
            // 将字节数组转换为Base64字符串
            String imageBase64 = Base64.getEncoder().encodeToString(imageBytes);
            fileInfo.setFileBlob(imageBase64);

        }
        result.put("picture",fileInfos);

        String path = request.getSession().getServletContext().getRealPath("/WEB-INF/classes/");

        String fileName = WordUtil.generateTouSuPdfPath("质量信息反馈单.pdf",path,config.filePath,result);

        return config.fileUrl+fileName;
    }


    private String complainAddLeagal(ComplainHandle complainHandle){

        String result = "";

        if (StringUtils.isBlank(complainHandle.getCustomer())){
            result = "请输入客户";
            return result;
        }

        if (StringUtils.isBlank(complainHandle.getComplainDate())){
            result = "请输入投诉日期";
            return result;
        }

        if (StringUtils.isBlank(complainHandle.getBatchNum())){
            result = "请输入批次号";
            return result;
        }

        if (StringUtils.isBlank(complainHandle.getOrderNum())){
            result = "请输入订单号";
            return result;
        }

        if (StringUtils.isBlank(complainHandle.getProblemDescription())){
            result = "请输入问题描述";
            return result;
        }

        return result;

    }

    private String complainUpdateLeagal(ComplainHandle complainHandle){
        String result = "";

        if (StringUtils.isBlank(complainHandle.getOpinion())){
            result = "请输入质量部意见";
            return result;
        }

        if (StringUtils.isBlank(complainHandle.getReasonAnalysis())){
            result = "请输入原因分析";
            return result;
        }

        if (StringUtils.isBlank(complainHandle.getResponsibleDeptName())){
            result = "请输入责任部门";
            return result;
        }

        if (StringUtils.isBlank(complainHandle.getResponsibleUserName())){
            result = "请输入责任人";
            return result;
        }

        result = complainAddLeagal(complainHandle);
        return result;
    }


    private String getDeptName(String userId){
        String deptName = departmentMapper.getDeptName(userId).getDeptName();
        return deptName;
    }


}
